package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.Company;
import org.dromara.admin.domain.Customer;
import org.dromara.admin.domain.Employee;
import org.dromara.admin.domain.vo.CustomerVo;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.service.IEmployeeService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.SupplierBo;
import org.dromara.admin.domain.vo.SupplierVo;
import org.dromara.admin.domain.Supplier;
import org.dromara.admin.mapper.SupplierMapper;
import org.dromara.admin.service.ISupplierService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 供应商信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SupplierServiceImpl implements ISupplierService {

    private final SupplierMapper baseMapper;
    private final IEmployeeService employeeService;

    /**
     * 查询供应商信息
     *
     * @param id 主键
     * @return 供应商信息
     */
    @Override
    public SupplierVo queryById(Long id) {
        SupplierVo supplierVo = baseMapper.selectVoById(id);
        if (BeanUtil.isEmpty(supplierVo)) {
            throw new ServiceException("供应商信息不存在！");
        }
        return supplierVo;
    }

    /**
     * 分页查询供应商信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 供应商信息分页列表
     */
    @Override
    public TableDataInfo<SupplierVo> queryPageList(SupplierBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Supplier> lqw = buildQueryWrapper(bo);
        Page<SupplierVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询当前登录用户的供应商信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 供应商信息分页列表
     */
    @Override
    public TableDataInfo<SupplierVo> queryPageMySupplierList(SupplierBo bo, PageQuery pageQuery) {
        // 获取当前登录用户的公司ID
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());
        bo.setCompanyId(employeeVo.getCompanyId());
        MPJLambdaWrapper<Supplier> mpjWrapper = getSupplierInfoByJoinTable(bo);
        Page<SupplierVo> result = baseMapper.selectJoinPage(pageQuery.build(), SupplierVo.class, mpjWrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 联表查询supplier、company和employee表
     */
    private static MPJLambdaWrapper<Supplier> getSupplierInfoByJoinTable(SupplierBo bo) {
        // 使用MPJBaseMapper进行联表查询supplier、company和employee表
        MPJLambdaWrapper<Supplier> mpjWrapper = new MPJLambdaWrapper<Supplier>()
            .selectAll(Supplier.class)
            .selectAssociation(Company.class, SupplierVo::getCompanyInfo)
            .selectAssociation(Employee.class, SupplierVo::getEmployeeInfo)
            .leftJoin(Company.class, Company::getId, Supplier::getCompanyId)
            .leftJoin(Employee.class, Employee::getId, Supplier::getCreatorId)
            .orderByDesc(Supplier::getCreateTime)
            .eq(bo.getCompanyId() != null, Supplier::getCompanyId, bo.getCompanyId())
            .eq(bo.getCreatorId() != null, Supplier::getCreatorId, bo.getCreatorId())
            .like(StringUtils.isNotBlank(bo.getSupplierName()), Supplier::getSupplierName, bo.getSupplierName())
            .like(StringUtils.isNotBlank(bo.getContactPerson()), Supplier::getContactPerson, bo.getContactPerson())
            .like(StringUtils.isNotBlank(bo.getPhone()), Supplier::getPhone, bo.getPhone())
            .like(StringUtils.isNotBlank(bo.getProvince()), Supplier::getProvince, bo.getProvince())
            .like(StringUtils.isNotBlank(bo.getCity()), Supplier::getCity, bo.getCity())
            .like(StringUtils.isNotBlank(bo.getDistrict()), Supplier::getDistrict, bo.getDistrict())
            .like(StringUtils.isNotBlank(bo.getDetailAddress()), Supplier::getDetailAddress, bo.getDetailAddress())
            .like(StringUtils.isNotBlank(bo.getRemark()), Supplier::getRemark, bo.getRemark());
        return mpjWrapper;
    }

    /**
     * 查询符合条件的供应商信息列表
     *
     * @param bo 查询条件
     * @return 供应商信息列表
     */
    @Override
    public List<SupplierVo> queryList(SupplierBo bo) {
        LambdaQueryWrapper<Supplier> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Supplier> buildQueryWrapper(SupplierBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Supplier> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(Supplier::getCreateTime);
        lqw.eq(bo.getCompanyId() != null, Supplier::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getCreatorId() != null, Supplier::getCreatorId, bo.getCreatorId());
        lqw.like(StringUtils.isNotBlank(bo.getSupplierName()), Supplier::getSupplierName, bo.getSupplierName());
        lqw.like(StringUtils.isNotBlank(bo.getContactPerson()), Supplier::getContactPerson, bo.getContactPerson());
        lqw.like(StringUtils.isNotBlank(bo.getPhone()), Supplier::getPhone, bo.getPhone());
        lqw.like(StringUtils.isNotBlank(bo.getProvince()), Supplier::getProvince, bo.getProvince());
        lqw.like(StringUtils.isNotBlank(bo.getCity()), Supplier::getCity, bo.getCity());
        lqw.like(StringUtils.isNotBlank(bo.getDistrict()), Supplier::getDistrict, bo.getDistrict());
        lqw.like(StringUtils.isNotBlank(bo.getDetailAddress()), Supplier::getDetailAddress, bo.getDetailAddress());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), Supplier::getRemark, bo.getRemark());
        return lqw;
    }

    /**
     * 新增供应商信息
     *
     * @param bo 供应商信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SupplierBo bo) {
        Supplier add = MapstructUtils.convert(bo, Supplier.class);
        EmployeeVo employeeVo = employeeService.queryById(add.getCreatorId());
        add.setCompanyId(employeeVo.getCompanyId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改供应商信息
     *
     * @param bo 供应商信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SupplierBo bo) {
        Supplier update = MapstructUtils.convert(bo, Supplier.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Supplier entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除供应商信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据主体公司id查询所属的供应商总数
     *
     * @param companyId 主体公司id
     * @return 供应商总数
     */
    @Override
    public Long querySupplierTotalByCompanyId(Long companyId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Supplier>().eq(Supplier::getCompanyId, companyId));
    }
}
